package middleware

import (
	"context"
	"github.com/zeromicro/go-zero/rest/httpx"
	"month2/C/api_C/internal/types"
	"month2/C/api_C/pkg"
	"net/http"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			response := types.Response{
				Msg:  "token为空",
				Data: nil,
				Code: 500,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		userId, err := pkg.ParseToken(token)
		if err != nil {
			response := types.Response{
				Msg:  "token无效",
				Data: nil,
				Code: 500,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		ext := context.WithValue(r.Context(), "UserId", userId)
		next(w, r.WithContext(ext))
		// Passthrough to next handler if need
		//next(w, r)
	}
}
